﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;


public class SaveHighScores : MonoBehaviour {
	public GUIText HighScoreText; 			//GUI HighScoreText
	static GUIText getHighScoreText;

	static string fileName = "foo.txt";
	static int highscoreMaxCount = 10;

	public static List<int> currentHighScores = new List<int>();

	// Use this for initialization
	void Start () {
		try
		{
			using (StreamReader sr = new StreamReader(Application.dataPath + "/" + fileName))
			{
				var fileContents = sr.ReadToEnd();
				sr.Close();
				
				var lines = fileContents.Split("\n"[0]);
				foreach (var line in lines) {
					if(line != string.Empty)
					{
						currentHighScores.Add(int.Parse(line));
					}
				}
			}
		}
		catch (IOException e)
		{
		}

		getHighScoreText = HighScoreText;
		if (currentHighScores.Count > 0) {
			HighScoreText.text = "HighScore: " + currentHighScores [0];
		} else {
			HighScoreText.text = "None";
		}
	}

	public static void AddScore(int score){
		if (currentHighScores.Count == 0) { //empty
			currentHighScores.Add(score);
			return;
		}

		int last = currentHighScores [currentHighScores.Count - 1];
		if (last > score){
			if(currentHighScores.Count <= highscoreMaxCount) { //worse than last
				currentHighScores.Add(score);
			}
			return;
		}

		for (int i = 0; i < currentHighScores.Count; i++) {
			if( currentHighScores[i] < score ){
				currentHighScores.Insert(i, score);
				break;
			}
		}

		if (currentHighScores.Count > highscoreMaxCount) {
			currentHighScores.RemoveAt( currentHighScores.Count-1 );
		}

		getHighScoreText.text = "HighScore:" + currentHighScores[0];
	}

	void OnApplicationQuit() {
		if(currentHighScores.Count > 0) {
			using (StreamWriter sw = new StreamWriter(Application.dataPath + "/" + fileName, false)) {
				foreach (var item in SaveHighScores.currentHighScores) {
					sw.WriteLine(item);
				}
			}
			currentHighScores.Clear();
		}
	}
}
